import numpy as np
import matplotlib.pyplot as plt
from sympy import symbols, limit, oo

def analyze_function():
    """函数渐近线综合分析"""
    x = symbols('x')
    f = (x**2 + 1) / (x - 1)
    
    print("=== 渐近线分析报告 ===")
    
    # 1. 铅直渐近线分析
    print("1. 铅直渐近线分析：")
    print(f"   分母为零的点：x = 1")
    
    # 2. 水平渐近线分析
    print("2. 水平渐近线分析：")
    limit_inf = limit(f, x, oo)
    print(f"   lim(x→∞) f(x) = {limit_inf}")
    
    # 3. 斜渐近线分析
    print("3. 斜渐近线分析：")
    a = limit(f/x, x, oo)
    b = limit(f - a*x, x, oo)
    print(f"   斜率 a = {a}")
    print(f"   截距 b = {b}")
    print(f"   斜渐近线方程：y = {a}x + {b}")
    
    return a, b

def plot_function():
    """绘制函数图像及渐近线"""
    # 设置中文字体
    plt.rcParams['font.sans-serif'] = ['SimHei']
    plt.rcParams['axes.unicode_minus'] = False
    
    x_vals = np.linspace(-10, 10, 1000)

    # 分别绘制左右两侧的图像，避免在x=1处连接
    x_left = np.linspace(-10, 0.9, 500)   # 左侧定义域
    x_right = np.linspace(1.1, 10, 500)    # 右侧定义域

    y_left = (x_left**2 + 1) / (x_left - 1)
    y_right = (x_right**2 + 1) / (x_right - 1)

    y_asymptote = x_vals + 1  # 斜渐近线：y = x + 1
    
    plt.figure(figsize=(12, 8))
    plt.plot(x_left, y_left, 'b-', label=r'$y = (x^2 + 1)/(x - 1)$', linewidth=2)
    plt.plot(x_right, y_right, 'b-', linewidth=2)
    plt.plot(x_vals, y_asymptote, 'r--', label='斜渐近线 y = x + 1', alpha=0.7, linewidth=2)
    plt.axvline(1, color='g', linestyle='--', label='铅直渐近线 x=1', alpha=0.7)
    
    plt.xlim(-8, 8)
    plt.ylim(-15, 15)
    plt.xlabel('x', fontsize=12)
    plt.ylabel('y', fontsize=12)
    plt.legend(fontsize=11)
    plt.title('函数渐近线综合分析', fontsize=14)
    plt.grid(True, alpha=0.3)
    plt.tight_layout()
    plt.show()

# 执行分析
a, b = analyze_function()
plot_function()